package com.uplift.mobile.realty.service.impl;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.uplift.mobile.rate.service.IRateService;
import com.uplift.mobile.realty.model.RealtyEarnings;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.github.pagehelper.PageHelper;
import com.uplift.common.Const;
import com.uplift.common.base.ServiceReslut;
import com.uplift.mobile.realty.dao.RealtyInfoMapper;
import com.uplift.mobile.realty.dao.RealtyRoomMapper;
import com.uplift.mobile.realty.model.RealtyInfo;
import com.uplift.mobile.realty.model.RealtyRoomModel;
import com.uplift.mobile.realty.service.IRealtyInfoService;
import com.uplift.sec.SecurityContext;

@Service
@Transactional
public class RealtyInfoServiceImpl implements IRealtyInfoService {

	@Autowired
	private RealtyInfoMapper realtyInfoMapper;

	@Autowired
	private RealtyRoomMapper realtyRoomMapper;
	@Autowired
	private IRateService rateService;

	@Override
	public List<Map<String, Object>> queryRealtyInfo(RealtyInfo realtyInfo) {
		PageHelper.startPage(realtyInfo.getPage(), realtyInfo.getLimit());

		if(StringUtils.isBlank(SecurityContext.getUserId())) {
			return null;
		}

		realtyInfo.setCustomerId(SecurityContext.getUserId());
		getRate(realtyInfo);

		List<Map<String, Object>> realtyInfos = this.realtyInfoMapper.selectRealtyInfo(realtyInfo);
        handRealtyInfoPic(realtyInfos);         //添加图片hosturl
		return realtyInfos;
	}

	private void handRealtyInfoPic(List<Map<String, Object>> realtyInfos) {
	    if(realtyInfos==null || realtyInfos.size()==0) {
	        return;
        }

        for (int i = 0; i < realtyInfos.size(); i++) {
            if(realtyInfos.get(i).get("picPath") != null) {
                realtyInfos.get(i).put("picPath", realtyInfos.get(i).get("picPath"));
            }
        }
    }

	@Override
	public ServiceReslut addRealtyInfo(RealtyInfo realtyInfo) throws Exception {

//		Map<String, Object> sessionUser = SecurityContext.getSessionUser();
//		if(sessionUser == null) {
//			return ServiceReslut.newServiceReslut(0, "获取登录用户信息失败");
//		}

//		realtyInfo.setCreateUserId((String) sessionUser.get("id"));

		CommonsMultipartFile cmf = realtyInfo.getFile();
		if(cmf != null) {
			FileItem item = cmf.getFileItem();
			String fileName = item.getName();
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
			String newFilePath = "product/" + newFileName;
			File file = new File(Const.DIR_UPLOAD_BASE + newFilePath);
			item.write(file);
			// 设置图片路径
			realtyInfo.setPicPath(newFilePath);
		}

		realtyInfo.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		realtyInfo.setState("1");
		realtyInfo.setCreateTime(new Date());

		saveRooms(realtyInfo.getRoomNum(), realtyInfo);

		return ServiceReslut.newServiceReslut(realtyInfoMapper.insertRealtyInfo(realtyInfo), "");
	}


	/**
	 * 新增roomNum
	 * @param roomNums
	 * @param realtyInfo
	 */
	public void saveRooms(String roomNums, RealtyInfo realtyInfo) {
		String[] rooms = StringUtils.split(roomNums, ",");
		RealtyRoomModel realtyRoomModel = null;
		for (String room : rooms) {
			realtyRoomModel = new RealtyRoomModel();
			realtyRoomModel.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			realtyRoomModel.setRealtyId(realtyInfo.getId());
			realtyRoomModel.setRoomNum(room);
			realtyRoomModel.setState("1");
			realtyRoomModel.setCreateTime(new Date());

			realtyInfo.setRoomId(realtyRoomModel.getId());
			realtyRoomMapper.insertRealtyRoom(realtyRoomModel);
		}
	}

	@Override
	public ServiceReslut updateRealtyInfo(RealtyInfo realtyInfo) throws Exception {

		CommonsMultipartFile cmf = realtyInfo.getFile();
		if(cmf != null) {
			FileItem item = cmf.getFileItem();
			String fileName = item.getName();
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
			String newFilePath = "product/" + newFileName;
			File file = new File(Const.DIR_UPLOAD_BASE + newFilePath);
			item.write(file);
			// 设置图片路径
			realtyInfo.setPicPath(newFilePath);
		}

		//更新公寓房间号
		if(StringUtils.isNoneBlank(realtyInfo.getRoomNum()) && StringUtils.equals(realtyInfo.getTypeCode(), "HOUSE")) {
			RealtyRoomModel realtyRoomModel = new RealtyRoomModel();
			realtyRoomModel.setRealtyId(realtyInfo.getId());
			realtyRoomModel.setRoomNum(realtyInfo.getRoomNum());
			realtyRoomModel.setUpdateTime(new Date());
			realtyRoomMapper.updateRealtyRoom(realtyRoomModel);
		}

		if(StringUtils.isNoneBlank(realtyInfo.getAddRoomNums()) && StringUtils.equals(realtyInfo.getTypeCode(), "BUILD")) {
			saveRooms(realtyInfo.getAddRoomNums(), realtyInfo);
			//更新房间信息
			updateRealtyRooms(realtyInfo);
		}
		realtyInfo.setUpdateTime(new Date());
		return ServiceReslut.newServiceReslut(realtyInfoMapper.updateRealtyInfo(realtyInfo), "");
	}

	//更新房间信息
	private void updateRealtyRooms(RealtyInfo realtyInfo) {
		//删除房间
		if(realtyInfo.getDelRooms()!=null && realtyInfo.getDelRooms().size()>0) {
			for (RealtyRoomModel delRoom : realtyInfo.getDelRooms()) {
				if(StringUtils.isBlank(delRoom.getId())) {
					continue;
				}
				delRoom.setState("0");		//删除状态
				delRoom.setUpdateTime(new Date());
				realtyRoomMapper.updateRealtyRoom(delRoom);
			}
		}

		//更新房间
		if(realtyInfo.getUpdateRooms()!=null && realtyInfo.getUpdateRooms().size()>0) {
			for (RealtyRoomModel updateRoom : realtyInfo.getUpdateRooms()) {
				if(StringUtils.isBlank(updateRoom.getId())) {
					continue;
				}

				updateRoom.setUpdateTime(new Date());
				realtyRoomMapper.updateRealtyRoom(updateRoom);
			}
		}
	}

	@Override
	public ServiceReslut deleteRealtyInfo(RealtyInfo realtyInfo) {
		realtyInfo.setState("0");		//删除状态
		realtyInfo.setUpdateTime(new Date());
		return ServiceReslut.newServiceReslut(realtyInfoMapper.updateRealtyInfo(realtyInfo), "");
	}

	/**
	 *  获取汇率
	 * @param realtyInfo
	 * @return
	 */
	private BigDecimal getRate(RealtyInfo realtyInfo) {
		BigDecimal rate = null;
		if(!StringUtils.isBlank(realtyInfo.getMoneyTypeCode()) && !StringUtils.equals(realtyInfo.getMoneyTypeCode(), "JPY")) {
			Map<String, Object> rateMap = rateService.queryMoenyRate(realtyInfo.getMoneyTypeCode());
			if(rateMap != null) {
				if(rateMap.get("rate") != null) {
					rate = (BigDecimal) rateMap.get("rate");
					realtyInfo.setRate(rate);
				}
			}
		} else {
			rate = new BigDecimal(1);
			realtyInfo.setRate(rate);
		}

		if(rate == null) {
			return null;
		}

		return rate;
	}

}
